package com.kun.base.net

import android.os.Build
import android.webkit.CookieManager
import com.alibaba.android.arouter.launcher.ARouter
import com.kun.base.env.Constants
import com.kun.base.env.Env
import com.kun.base.util.MMKVUtils
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancel
import kotlinx.coroutines.withContext

/**
 * 对外提供统一的获取请求服务实例
 *  @author : Kun
 *  @date : 2021/4/13
 *  @time : 15:20
 */
class Api {
    companion object {
        /**
         * 获取请求服务实例
         * 默认baseurl
         */
        fun <T> getInstance(clazz: Class<T>): T = getInstanceWithBaseUrl(clazz, Env.getDomain())


        /**
         * 获取指定Url请求的服务实例
         *
         * @param clazz   服务实例类型
         * @param baseUrl 指定的BaseUrl
         * @param <T>     泛型
         * @return 指定的服务类型和Url的实例
         */
        fun <T> getInstanceWithBaseUrl(clazz: Class<T>, baseUrl: String): T =
            ApiManager.getServiceWithBaseUrl(clazz, baseUrl)

        /**
         * 接口请求
         */
        suspend inline fun <T> apiCall(crossinline call: suspend CoroutineScope.() -> ResponseResult<T>): ResponseResult<T> {
            return withContext(Dispatchers.IO) {
                val res: ResponseResult<T>
                try {
                    res = call()
                } catch (e: Throwable) {
                    return@withContext ApiException.build(e).toResponseResult<T>()
                }

                if (res.errorCode == ApiException.CODE_LOGIN) {
                    //登录
                    MMKVUtils.remove(Constants.USERNAME_CACHE_KEY)
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        CookieManager.getInstance().removeAllCookies(null)
                    }else{
                        CookieManager.getInstance().removeAllCookie()
                    }
                    ARouter.getInstance().build("/main/LoginActivity").navigation()
                    cancel()
                }
                return@withContext res
            }
        }

    }

}